﻿#include "debugTcp.h"

debugTcp::debugTcp(QWidget* parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    QPalette pal;
   

    setFixedSize(width(),height());
    setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);
    ui.writeBtn->setEnabled(false);
    initClient();
    connect(client, &QTcpSocket::connected, this, &debugTcp::connectYes);
    connect(client, &QTcpSocket::disconnected, this, &debugTcp::connectDis);
    connect(client, &QTcpSocket::errorOccurred, this, &debugTcp::connectError);
    connect(client, &QTcpSocket::readyRead, [this] {
        auto reads = client->readAll();
        ui.plainTextEdit->appendPlainText(reads);
        });
}

debugTcp::~debugTcp()
{}

void debugTcp::on_writeBtn_clicked()
{
    const QByteArray send_data = ui.sendLine->text().toUtf8().append("\n");
    if (send_data.isEmpty())
        return;
    client->write(send_data);
    client->flush();
    ui.plainTextEdit->appendPlainText("[本机]: " + send_data);
}

void debugTcp::on_disBtn_clicked()
{
    client->disconnectFromHost();
}

void debugTcp::on_connectBtn_clicked()
{
    auto ip = ui.ipLine->text();
    auto port = ui.portLine->text();
    const QHostAddress address = QHostAddress(ip);
    const unsigned short sPort = port.toUShort();
    client->connectToHost(address, sPort);
    ui.connectBtn->setText("连接中...");
    ui.connectBtn->setEnabled(false);
}

void debugTcp::initClient()
{
    client = new QTcpSocket(this);
}

void debugTcp::closeEvent(QCloseEvent* event)
{
    client->close();
    client->deleteLater();
    close();
}

void debugTcp::connectYes()
{
    ui.connectBtn->setText("连接");
    ui.connectBtn->setEnabled(true);
    ui.connectStatus->setText("连接成功");
    ui.connectBtn->setEnabled(false);
    ui.connectStatus->setChecked(true);
    ui.writeBtn->setEnabled(true);
}

void debugTcp::connectDis()
{
    ui.connectStatus->setText("连接断开");
    ui.connectStatus->setChecked(false); 
    ui.writeBtn->setEnabled(false); 
    ui.connectBtn->setEnabled(true);
}

void debugTcp::connectError()
{
    ui.connectStatus->setText("连接失败");
    ui.connectBtn->setText("连接");
    ui.connectBtn->setEnabled(true);
    ui.connectStatus->setChecked(false);
    ui.writeBtn->setEnabled(false);
}
